/*
 * @Author: your name
 * @Date: 2022-03-29 14:28:42
 * @LastEditTime: 2022-04-26 13:41:04
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \operation-platform-ui\src\store\modules\permission.js
 */
import { asyncRouterMap, constantRouterMap } from '@/config/router.config';

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false;
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i].code);
      if (flag) {
        return true;
      }
    }
    return false;
  }
  return true;
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id);
  } else {
    return true;
  }
}

function filterAsyncRouter(routerMap, permissions) {
  const result = [];
  routerMap.forEach(route => {
    const newRoute = Object.assign({}, route);
    if (hasPermission(permissions, newRoute)) {
      result.push(newRoute);
      if (newRoute.children && newRoute.children.length) {
        newRoute.children = filterAsyncRouter(newRoute.children, permissions);
      }
    }
  });
  return result;
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({ commit }, permissions) {
      return new Promise(resolve => {
        const accessedRouters = filterAsyncRouter(asyncRouterMap, permissions);        
        commit('SET_ROUTERS', accessedRouters);
        resolve();
      });
    }
  }
};

export default permission;
